#! /usr/bin/python
# -*- coding: UTF-8 -*-
import urllib
from cStringIO import StringIO

class StatusBox():
    def __init__(self, parent):
        self.parent = parent
        self.Log = self.parent.Log
        
    def RefreshStatusWidget(self):
        if self.parent.opt_twitter_username == '' and self.parent.opt_twitter_password == '':
            self.Log('No credentials')
            return

        try:
            statuses_json   = self.parent.twit_api.status_friends_timeline()
        except:
            self.Log('Bad credentials')
            return

        # Set task bar icon to refreshing one
        self.parent.ChangeAppIcon(refresh_png_icon)

        statuses        = simplejson.loads(statuses_json)

        # Set reply icon
        reply_image = wx.Image(reply_png_icon)
        reply_image.Rescale(36, 36)
        self.reply_icon = reply_image.ConvertToBitmap()

        # Clear sizer
        self.parent.status_box.sizer.Clear(True)
        
        for status in statuses:
            user_id = status['user']['id']
            self.parent.tweet_users[user_id] = status['user']['screen_name']
            
            self.StatusWidget(
                status['text'],
                status['created_at'],
                status['user']['screen_name'],
                status['user']['profile_image_url'],
                user_id
            )

        # Fit sizer to a new set
        self.parent.status_box.sizer.Fit(self.parent.status_box)
        
        # Restore taskbar icon
        self.parent.ChangeAppIcon(png_icon)

    def StatusWidget(self, status_text, status_created, user_screen_name, user_img, status_user_id):
        window = self.parent.status_box
        
        if user_img != '':
            user_img_bmp = self.GetUserImage(status_user_id)
            if user_img_bmp is False:
                self.SetUserImage(user_img, status_user_id)
                user_img_bmp = self.GetUserImage(status_user_id)
            self.status_user_image  = wx.StaticBitmap(window, -1, user_img_bmp)
            self.status_user_image.SetSize(self.status_user_image.GetBestSize())

        self.Log('Processing status widget for ' + user_screen_name)
        
        # Parse status text and set it
        self.status_text        = wx.StaticText(window, -1, self.ParseStatusText(status_text), size=(300,-1))

        # Reply button - set id as users id so we know to who we're replying to (accident waiting to happen)
        # TODO: Solve the mistery behind passing variables on events (as in: which button did I click, to who am I replying)
        self.status_reply       = wx.BitmapButton(window, status_user_id, self.reply_icon, style=wx.NO_BORDER)
        self.status_reply.SetSize((24, 24))
        self.status_reply.Bind(wx.EVT_BUTTON, self.parent.events.OnReplyButtonClick)

        window.sizer.Add(self.status_user_image, 0, wx.EXPAND, 0)
        window.sizer.Add(self.status_text, 0, wx.EXPAND|wx.FULL_REPAINT_ON_RESIZE, 0)
        window.sizer.Add(self.status_reply, 0, 0, 0)

    def ParseStatusText(self, status_text):
        return status_text

    def GetUserImage(self, user_id):
        user_image = __ASSETS_DIR__ + str(user_id) + '.bmp'
        if os.path.exists(user_image):
            bmp = wx.Bitmap(user_image)
            return bmp
        else:
            return False

    def SetUserImage(self, image_str, user_id):
        user_image = __ASSETS_DIR__ + str(user_id) + '.bmp'
        fp = urllib.urlopen(image_str)
        data = fp.read()
        fp.close()
        image = wx.ImageFromStream(StringIO(data))
        bmp = image.ConvertToBitmap()
        bmp.SaveFile(user_image, wx.BITMAP_TYPE_BMP)